package com.lry.thompson;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

public class DfaManager {

    public static int DFA_STATE_NUM = 1;
    public static Map<Integer,Dfa> STATE_NUM_2_DFA = new HashMap<>();
    public static Map<Dfa,Integer> DFA_2_STATE_NUM = new HashMap<>();
    public static Dfa start;
    public static Stack<Dfa> stack = new Stack<>();


    public static boolean isEnd(Integer stateNum){
        Dfa dfa = STATE_NUM_2_DFA.get(stateNum);
        if(null==dfa){
            return false;
        }
        return dfa.accepted;
    }

    public static Dfa getDfa(Set<Nfa> input){
        Dfa dfa = new Dfa(input);
        Integer stateNum = DFA_2_STATE_NUM.get(dfa);
        if(null!=stateNum){
            //老节点直接返回
            return STATE_NUM_2_DFA.get(stateNum);
        }else{
            dfa.stateNum = DFA_STATE_NUM++;
            //新构建一个dfa节点
            for(Nfa nfa:input){
                if(nfa.isEndNfa()){
                    dfa.accepted = true;
                    break;
                }
            }
        }
        //新节点才会走到这
        if(DFA_2_STATE_NUM.isEmpty()){
            start = dfa;
        }
        stack.push(dfa);
        DFA_2_STATE_NUM.put(dfa, dfa.stateNum);
        STATE_NUM_2_DFA.put(dfa.stateNum,dfa);
        return dfa;
    }


}
